package br.com.lucasddaniel.inbuzios.activities;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import br.com.lucasddaniel.inbuzios.Controller;
import br.com.lucasddaniel.inbuzios.R;
import br.com.lucasddaniel.inbuzios.adapter.PasseiosRelatorioAdapter;
import br.com.lucasddaniel.inbuzios.bean.BluetoothConnector;
import br.com.lucasddaniel.inbuzios.bean.Device;
import br.com.lucasddaniel.inbuzios.bean.PacoteArquivoBean;
import br.com.lucasddaniel.inbuzios.bean.PasseioBean;
import br.com.lucasddaniel.inbuzios.dao.ExcessaoBanco;

import com.androidquery.AQuery;
import com.datecs.api.printer.Printer;
import com.datecs.api.printer.ProtocolAdapter;
import com.datecs.api.printer.ProtocolAdapter.Channel;
import com.devsmart.android.ui.HorizontalListView;

public class RelatoriosActivity extends Activity {

	private AQuery aq;

	private final Handler mHandler = new Handler();
	private BluetoothConnector mBthConnector;
	private Printer mPrinter;
	private ProgressDialog mProgressDialog;

	private HorizontalListView lvPasseios;
	private PasseiosRelatorioAdapter passeiosAdapter;
	private List<PasseioBean> listPasseios;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_relatorio_passeio);
		// aq = new AQuery(this);
		// aq.id(R.id.button).text("Click Me").clicked(this, "buttonClicked");
		try {
			listPasseios = Controller.getInstance().listaPasseios(
					getApplicationContext());
		} catch (ExcessaoBanco e) {
			e.printStackTrace();
		}
		initializeComponents();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mHandler.post(new Runnable() {
			public void run() {
				AlertDialog dlg = new AlertDialog.Builder(RelatoriosActivity.this).setTitle("Informação").setMessage("Um clique rápido acessa os dados do passeio para alterar. \n Um clique longo imprime segunda via.").create();
				dlg.show();
			}
		});
	}
	
	private void initializeComponents() {
		lvPasseios = (HorizontalListView) findViewById(R.id_activity_listar_passeios.listview);
		lvPasseios.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				if (Controller.isVersaoproducao()) {
					final int pos = position;
					new Thread() {
	                    @Override
	                    public void run() {
	                    	showProgress("Imprimindo");
	                    	if (Controller.isVersaoproducao()) {
		                        doPrintImage();
		                        imprimePasseio(passeiosAdapter.getItem(pos));
	                    	}
	                        Intent i = new Intent(getApplicationContext(), MenuActivity.class);
	                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                        dismissProgress();
	                        startActivity(i);
	                    }
	                }.start();
				}
				return false;
			}
		});

		passeiosAdapter = new PasseiosRelatorioAdapter(getApplicationContext(),
				R.layout.row_passeio, listPasseios);
		lvPasseios.setAdapter(passeiosAdapter);
		lvPasseios
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						Intent it = new Intent(RelatoriosActivity.this,
								RelatorioPacotesActivity.class);
						it.putExtra("idPasseio",
								passeiosAdapter.getItem(position).getId());
						startActivity(it);
					}
				});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		if (Controller.isVersaoproducao()) {
			mConnectThread.start();
		}
	}
	private void imprimePasseio(PasseioBean passeio) {
		StringBuffer sb = new StringBuffer();
		Calendar c = Calendar.getInstance();
		sb.append("{reset}Guia: " + Controller.getInstance().getResponsavelLogado().getLogin() + "{br}");
		sb.append("{reset}Voucher: {b}" + passeio.getId() + "{br}");
		sb.append("{reset}Fone: +55 22-2623-6033{br}");
		sb.append("{reset}Nextel: 36676*25{br}");
		SimpleDateFormat sdfData = new SimpleDateFormat("dd/MM/yy HH:mm");
		sb.append("{reset}Data: " + sdfData.format(c.getTime()) + "{br}");
		sb.append("{reset}Nome: {b}" + passeio.getNomeTurista() + "{br}");
		sb.append("{reset}Pousada: " + passeio.getNomePousada() + "{br}");
		sb.append("{reset}--------------------------------{br}");
		for (PacoteArquivoBean pac : passeio.getPacotes()) {
			sb.append("{reset}{b}" + pac.getNome() + "{br}");
			sb.append("{reset}{b}Hora: " + sdfData.format(pac.getDataHoraSaida()) + "{br}");
			sb.append("{reset}Qtd: " + pac.getQuantidade() + "{br}");
//			try {
//				for (PacoteArquivoBean pc : Controller.getInstance().listarPacotesArquivo()) {
//					if (pac.getNome().equalsIgnoreCase(pc.getNome())) {
//						sb.append("{reset}Obs: " + pc.getTransporte() + "{br}{br}");
//						break;
//					}
//				}
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} catch (ExcessaoBanco e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
		}
		sb.append("{reset}--------------------------------{br}");
		sb.append("{reset}{b}Valor: " + passeio.getTotalGeral() + " -> " + passeio.getTipoDeMoeda() + "{br}");
		if (passeio.getDesconto() == null) {
			sb.append("{reset}{b}Desconto: 0{br}");
		} else {
			sb.append("{reset}{b}Desconto: " + passeio.getDesconto() + "{br}");
		}
		if (passeio.getSinal() == null) {
			sb.append("{reset}{b}Sinal: 0" + "{br}");
		} else {
			sb.append("{reset}{b}Sinal: " + passeio.getSinal() + "{br}");
		}
		sb.append("{reset}{b}Saldo: " + passeio.getSaldoFinal() + "{br}{br}");
		sb.append("{reset}{b}Obs: " + passeio.getObs() == null ? "" : passeio.getObs() + "{br}");

		try {
			mPrinter.reset();
			mPrinter.printTaggedText(sb.toString());
			mPrinter.feedPaper(110);
		} catch (IOException e) {
			e.printStackTrace();
			error(R.drawable.printer_icon, "Falha ao imprimir o cupom. " + e.getMessage());
		}
	}

	private final Thread mConnectThread = new Thread() {
		@Override
		public void run() {
			Looper.prepare();
			showProgress("conectando...");
			Device device = null;
			try {
				device = Controller.getInstance().buscarDevicePrincipal(
						getApplicationContext());
			} catch (ExcessaoBanco e) {
				e.printStackTrace();
				dismissProgress();
				showProgress(e.getMessage());
			}
			Log.d("BLUETOOTH", device.getEndereco());
			connectBth(device.getEndereco());
			dismissProgress();
			Looper.loop();
		}

		void connectBth(String address) {

			try {
				mBthConnector = BluetoothConnector
						.getConnector(RelatoriosActivity.this);
				mBthConnector.connect(address);
				mPrinter = getPrinter(mBthConnector.getInputStream(),
						mBthConnector.getOutputStream());
			} catch (IOException e) {
				Log.d("BLUETOOTH", e.getMessage());
				e.printStackTrace();
				error(R.drawable.bluetooth, e.getMessage());
				return;
			}
		}

		Printer getPrinter(InputStream in, OutputStream out) throws IOException {
			ProtocolAdapter adapter = new ProtocolAdapter(in, out);
			Printer printer = null;

			if (adapter.isProtocolEnabled()) {
				Channel channel = adapter
						.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
				InputStream newIn = channel.getInputStream();
				OutputStream newOut = channel.getOutputStream();
				printer = new Printer(newIn, newOut);
			} else {
				printer = new Printer(in, out);
			}

			return printer;
		}
	};

	@Override
	protected void onStop() {
		super.onStop();
		if (mBthConnector != null) {
			try {
				mBthConnector.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void showProgress(final String text) {
		mHandler.post(new Runnable() {
			public void run() {
				mProgressDialog = ProgressDialog.show(RelatoriosActivity.this,
						"Aguarde um momento...", text, true);
			}
		});
	}

	private void dismissProgress() {
		mHandler.post(new Runnable() {
			public void run() {
				mProgressDialog.dismiss();
			}
		});
	}

	private void error(final int resIconId, final String message) {
		mHandler.post(new Runnable() {
			public void run() {
				AlertDialog dlg = new AlertDialog.Builder(
						RelatoriosActivity.this).setTitle("Error")
						.setMessage(message).create();
				dlg.setIcon(resIconId);
				dlg.setOnDismissListener(new OnDismissListener() {
					public void onDismiss(DialogInterface dialog) {
						RelatoriosActivity.this.finish();
					}
				});
				dlg.show();
			}
		});
	}
	
	private void doPrintImage() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        final int[] argb = new int[width * height];
        bitmap.getPixels(argb, 0, width, 0, 0, width, height);

        try {
            mPrinter.reset();
            mPrinter.printImage(argb, width, height, Printer.ALIGN_CENTER, true);
        } catch (IOException e) {
            error(R.drawable.printer_icon, "Falha ao imprimir o cupom. " + e.getMessage());
        }
    }
}
